package com.meida.paotui.app.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.jpush.api.JPushClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.RefundOrder;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.egzosn.pay.wx.api.WxPayConfigStorage;
import com.egzosn.pay.wx.api.WxPayService;
import com.meida.common.annotation.LoginRequired;
import com.meida.common.base.handler.SmsSendHandler;
import com.meida.common.constants.SettingConstant;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.PageModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.*;
import com.meida.module.marketing.provider.service.impl.CouponUserServiceImpl;
import com.meida.module.pay.client.entity.PayConfig;
import com.meida.module.pay.provider.response.PayResponse;
import com.meida.module.pay.provider.service.PayConfigService;
import com.meida.module.push.provider.factory.PushFactory;
import com.meida.module.system.client.entity.SysArea;
import com.meida.module.system.provider.service.SysAreaService;
import com.meida.module.user.client.entity.AppAccount;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import com.meida.module.user.provider.service.impl.AppAccountServiceImpl;
import com.meida.msg.client.model.SmsMessage;
import com.meida.msg.provider.service.impl.AliyunSmsSenderImpl;
import com.meida.paotui.bus.client.entity.*;
import com.meida.paotui.bus.provider.mapper.BusProfitMapper;
import com.meida.paotui.bus.provider.mapper.BusTradeMapper;
import com.meida.paotui.bus.provider.model.PayParam;
import com.meida.paotui.bus.provider.model.RequestHandler;
import com.meida.paotui.bus.provider.service.*;
import com.meida.paotui.bus.provider.service.impl.BusGoodsorderServiceImpl;
import com.meida.paotui.bus.provider.utils.GetWxOrderno;
import com.meida.paotui.bus.provider.utils.PcUtils;
import com.meida.paotui.bus.provider.utils.RedisGeoUtils;
import com.meida.paotui.bus.provider.utils.TenpayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;


@RestController
@Api(tags = "订单模块")
public class OrderController {
    @Autowired
    private BusGoodsorderServiceImpl busGoodsorderService;
    @Autowired
    private CouponUserServiceImpl couponService;
    @Autowired
    private BusCommonaddressService buscommonaddressService;
    @Autowired
    private RedisGeoUtils redisGeoUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private BusEvaluateService busevaluateService;
    @Autowired
    private BusMsgreceiveService busmsgreceiveService;
    @Autowired
    private BusTradeService bustradeService;
    @Resource
    private BusTradeMapper tradeMapper;
    @Autowired
    private AppUserService userService;
    @Autowired
    private BusRiderService busRiderService;
    @Autowired
    private BusSysconfigService sysconfigService;
    @Autowired
    private BusProfitService busProfitService;
    @Autowired
    private OrderNoUtil orderNoUtil;
    @Autowired
    private PushFactory<JPushClient> myPushFactory;
    @Autowired
    private BusCustomerdetailService busCustomerdetailService;
    @Resource
    private BusProfitMapper busprofitmapper;
    @Autowired
    private PayConfigService payConfigService;
    @Resource
    private BusTradeMapper busTradeMapper;
    @Autowired
    private BusIdentityService identityService;
    @Autowired
    private BusScheduleService busScheduleService;
    @Autowired
    private AppAccountServiceImpl accountService;
    @Autowired
    private SysAreaService areaService;
    public final static String PAY_UNIFIEDORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    public final static String PAY_REFUND = "https://api.mch.weixin.qq.com/secapi/pay/refund";// 退款
    public final static String mch_id = "1524077011";
    public final static String mch_key = "d1s5ad12e3wq1ds2a31dwe5631d3wa1d";
    public final static String appid = "wxb18671ec9a241a50";
    public final static String appsecret = "c91c742b4db43dea0e6cfa403a0838a1";

    @PostMapping(value = "/order/addOrder")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "goods", value = "账户名", paramType = "form"),
        @ApiImplicitParam(name = "buyAddress", value = "取货地址", paramType = "form"),
        @ApiImplicitParam(name = "buyLng", value = "取货经度", paramType = "form"),
        @ApiImplicitParam(name = "buyLat", value = "取货纬度", paramType = "form"),
        @ApiImplicitParam(name = "commission", value = "佣金", paramType = "form"),
        @ApiImplicitParam(name = "weight", value = "配送重量", paramType = "form"),
        @ApiImplicitParam(name = "buyDetailAdress", value = "取件详细地址", paramType = "form"),
        @ApiImplicitParam(name = "receiptAddress", value = "收件详细地址", paramType = "form"),
        @ApiImplicitParam(name = "receiptLng", value = "收件经度", paramType = "form"),
        @ApiImplicitParam(name = "receiptLat", value = "收件纬度", paramType = "form"),
        @ApiImplicitParam(name = "distance_text", value = "配送距离", paramType = "form"),
        @ApiImplicitParam(name = "status", value = "订单状态", paramType = "form", defaultValue = "0")
    })
    public ResultBody save(@ModelAttribute(value = "saveModel") BusGoodsorder goodsorder, Long couponId, Double weight, String commonAddressId, String buycommonAddressId, Double distance, ResultBody resultBody) {
        EntityMap resultmap = new EntityMap();
        Long userId = OpenHelper.getUserId();
        goodsorder.setUserId(userId);
        //获取发单人信息
        AppUser user=userService.getUserById(userId);
        goodsorder.setSendPersonName(user.getUserName());
        goodsorder.setSendPersontel(user.getMobile());
        QueryWrapper<BusIdentity> qw_i = new QueryWrapper();
        qw_i.eq("userId", userId);

        if (FlymeUtils.isNotEmpty(buycommonAddressId)) {
            CriteriaQuery qw = new CriteriaQuery(BusCommonaddress.class);
            qw.eq("UserId", OpenHelper.getUserId());
            qw.eq("commonAddressId", buycommonAddressId);
            EntityMap c = buscommonaddressService.findOne(qw);
            if (c == null) {
                return ResultBody.failed ("取货地址不存在");
            }
            QueryWrapper<SysArea> area_qw=new  QueryWrapper();
            area_qw.like("areaName",c.get("city"));
            SysArea area=areaService.getOne(area_qw);

            QueryWrapper<BusSchedule> qw_bs=new QueryWrapper();
            qw_bs.eq("cityId",area.getAreaId());
            BusSchedule busSchedule=busScheduleService.getOne(qw_bs);

            if (FlymeUtils.isNotEmpty(c)) {
                if(FlymeUtils.isNotEmpty(busSchedule)&&FlymeUtils.isNotEmpty(busSchedule.getRegionJson())){
                    //判断坐标是否在区域范围内
                    JSONArray array= JSONUtil.parseArray(busSchedule.getRegionJson());
                    Point[] points=new Point[array.size()];
                    int i=0;
                    for (Object s : array) {
                        JSONArray arr=(JSONArray)s;
                        Point point=new Point(arr.getDouble(0),arr.getDouble(1));
                        points[i]=point;
                        i++;
                    }
                    boolean a=busScheduleService.isPtInPoly(Double.parseDouble(c.get("lng")),Double.parseDouble(c.get("lat")), points);
                    if(!a){
                        return ResultBody.failed ("取件地址不在配送范围内");
                    }
               }
                goodsorder.setBuyProvince(c.get("province"));
                goodsorder.setBuyAddress(c.get("address"));
                goodsorder.setBuyCity(c.get("city"));
                goodsorder.setBuyDistrict(c.get("district"));
                goodsorder.setBuyLng(c.get("lng"));
                goodsorder.setBuyLat(c.get("lat"));
                goodsorder.setBuyTownship(c.get("township"));
                goodsorder.setBuyVillage(c.get("village"));
                goodsorder.setBuyDetailAdress(c.get("detailAdress"));
                goodsorder.setBuyMobile(c.get("mobile"));
                goodsorder.setBuyname(c.get("name"));
            }
        }
        if (ObjectUtils.isNotEmpty(commonAddressId)) {
            CriteriaQuery qw = new CriteriaQuery(BusCommonaddress.class);
            qw.eq("UserId", OpenHelper.getUserId());
            qw.eq("commonAddressId", commonAddressId);
            EntityMap d = buscommonaddressService.findOne(qw);
            if (d == null) {
                resultBody.setMsg("收货地址不存在");
                return resultBody;
            }
            QueryWrapper<SysArea> area_qw=new  QueryWrapper();
            area_qw.like("areaName",d.get("city"));
            SysArea area=areaService.getOne(area_qw);

            QueryWrapper<BusSchedule> qw_bs=new QueryWrapper();
            qw_bs.eq("cityId",area.getAreaId());
            BusSchedule busSchedule=busScheduleService.getOne(qw_bs);
            if(FlymeUtils.isNotEmpty(busSchedule)&&FlymeUtils.isNotEmpty(busSchedule.getRegionJson())){
                //判断坐标是否在区域范围内
                JSONArray array= JSONUtil.parseArray(busSchedule.getRegionJson());
                Point[] points=new Point[array.size()];
                int i=0;
                for (Object s : array) {
                    JSONArray arr=(JSONArray)s;
                    Point point=new Point(arr.getDouble(0),arr.getDouble(1));
                    points[i]=point;
                    i++;
                }
                boolean a=busScheduleService.isPtInPoly(Double.parseDouble(d.get("lng")),Double.parseDouble(d.get("lat")), points);
                if(!a){
                    return ResultBody.failed ("收件地址不在配送范围内");
                }
            }
            goodsorder.setGoodsOrderId(Long.parseLong(orderNoUtil.getOrderNo()));
            goodsorder.setReceiptProvince(d.get("province"));
            goodsorder.setReceiptAddress(d.get("address"));
            goodsorder.setReceiptCity(d.get("city"));
            goodsorder.setReceiptDistrict(d.get("district"));
            goodsorder.setReceiptLng(d.get("lng"));
            goodsorder.setReceiptLat(d.get("lat"));
            goodsorder.setReceiptTownship(d.get("township"));
            goodsorder.setReceiptVillage(d.get("village"));
            goodsorder.setReceiptDetailAdress(d.get("detailAdress"));
            goodsorder.setReceiptMobile(d.get("mobile"));
            goodsorder.setReceiptName(d.get("name"));
        }
        //判断前端结算地图导航距离
        Double commission = 0.00;
        if (FlymeUtils.isEmpty(distance)) {
            return ResultBody.failed("送货实际距离不能为空");
        } else if (FlymeUtils.isEmpty(weight)) {
            return ResultBody.failed("重量不能为空");
        } else {
            if (ObjectUtils.isEmpty(goodsorder.getTip())) {
                goodsorder.setTip(BigDecimal.ZERO);
            }
            commission = busGoodsorderService.getCommission(distance, weight, couponId, goodsorder.getTip().doubleValue());
            DecimalFormat df = new DecimalFormat("#.00");
            BigDecimal bg = new BigDecimal(commission);
            Double newdistance= Math.ceil(distance / 1000);
            goodsorder.setDistance(newdistance);//配送取整计算距离
            goodsorder.setRealdistance(Double.parseDouble(df.format(distance / 1000)));//步行实际距离
            if (bg.setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(goodsorder.getCommission()) != 0) {
                return ResultBody.failed("发布订单失败，配送费参数不正确");
            }
            //读取高峰期配置计算配送费
            if (ObjectUtils.isNotEmpty(goodsorder.getReceiptTime())) {
                //判断时间范围是否在高峰期，处在高峰期时候加价配送费
                QueryWrapper<BusSysconfig> qw_con=new QueryWrapper();
                qw_con.in("configType","morningcharge","eveingcharge");
                List<BusSysconfig> busSysconfig=sysconfigService.list(qw_con);
                String datatime=goodsorder.getReceiptTime();
                datatime=datatime .substring(11,goodsorder.getReceiptTime().length());
                Long newTime= DateUtil.parse(datatime, DatePattern.NORM_TIME_PATTERN).getTime();
                if (busSysconfig.size() > 0) {
                    for (BusSysconfig time : busSysconfig) {
                        if(FlymeUtils.isNotEmpty(time.getStartHighTime())&&FlymeUtils.isNotEmpty(time.getEndHighTime())){
                            Long startTime= DateUtil.parse(time.getStartHighTime(),DatePattern.NORM_TIME_PATTERN).getTime();
                            Long endTime= DateUtil.parse(time.getEndHighTime(),DatePattern.NORM_TIME_PATTERN).getTime();
                            if(newTime> startTime&&newTime<endTime){
                                Double c_val = Double.parseDouble(time.getConfigVal());//高峰期配送费
                                commission = commission + c_val.doubleValue();
                            }
                        }
                    }
                }
            }
            goodsorder.setCommission(BigDecimal.valueOf(commission));
            goodsorder.setRealPaySum(BigDecimal.valueOf(commission));
            QueryWrapper<BusSysconfig> qw_q = new QueryWrapper();
            qw_q.eq("configType", "commisonrate");
            BusSysconfig config = sysconfigService.getOne(qw_q);
            Double ridecomssion = 0.00;
            if (FlymeUtils.isNotEmpty(config)) {
                Double val = Double.parseDouble(config.getConfigVal());
                Double comssionval = goodsorder.getCommission().doubleValue();
                ridecomssion = comssionval * val;
                Double plotcomssion = comssionval * (1 - val);
                //下单成功后根据订单参数计算平台佣金与骑手服务费
                goodsorder.setPlatformCommission(BigDecimal.valueOf(plotcomssion).setScale(2, BigDecimal.ROUND_HALF_UP));
                goodsorder.setRiderCommission(BigDecimal.valueOf(ridecomssion).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        }
        goodsorder.setStatus(0);//默认未支付状态
        Boolean a = busGoodsorderService.save(goodsorder);
        if (a) {
            resultmap.put("goodsOrderId", goodsorder.getGoodsOrderId());
        }
        return ResultBody.ok(resultmap);
    }

    @ApiOperation(value = "获取佣金", notes = "获取佣金")
    @PostMapping(value = "/order/getCommission")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "distance", value = "运输距离", paramType = "form"),
        @ApiImplicitParam(name = "weight", value = "货物重量", paramType = "form")
    })
    public ResultBody getCommission(Double distance, Double weight, Long couponId, Double tip, ResultBody resultBody) {
        if (FlymeUtils.isEmpty(distance)) {
            return ResultBody.failed("送货实际距离不能为空");

        }
        if (FlymeUtils.isEmpty(weight)) {
            return ResultBody.failed("货物重量不能为空");
        }
        Double commission = busGoodsorderService.getCommission(distance, weight, couponId, tip);
        return ResultBody.ok(commission);
    }

    @ApiOperation(value = "我的优惠券", notes = "我的优惠券")
    @PostMapping(value = "/voucher/getvoucher")
    public ResultBody getvoucher(PageModel pageModel) {
        ResultBody resultBody = busCustomerdetailService.cutomerpageList(pageModel);
        return resultBody;
    }

    @ApiOperation(value = "查看订单详情", notes = "查看订单详情")
    @PostMapping(value = "/order/getOrderdeatil")
    public ResultBody getOrderdeatil(String goodsOrderId) {
        ResultBody resultBody = new ResultBody();
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");

        }
        EntityMap map = new EntityMap();
        BusGoodsorder goodsOrder = busGoodsorderService.getById(goodsOrderId);
        if (FlymeUtils.isNotEmpty(goodsOrder.getCouponId())) {
            EntityMap coupon = couponService.getCoupon(goodsOrder.getCouponId());
            map.put("couponTitle", coupon.get("couponTitle"));
        } else {
            map.put("couponTitle", "");
        }
        AppUser user = userService.getUserById(goodsOrder.getSendUserInfoId());
        if (FlymeUtils.isNotEmpty(user)) {
            map.put("sendUser", user);
        } else {
            map.put("sendUser", new Object());
        }
        map.put("goodsOrder", goodsOrder);
        //根据userId 获取redis 缓存中骑手位置
        if (ObjectUtils.isNotEmpty(goodsOrder.getSendUserInfoId())) {
            List<Point> point = redisGeoUtils.getGeo("location", String.valueOf(goodsOrder.getSendUserInfoId()));
            if (FlymeUtils.isNotEmpty(point)) {
                map.put("point", point);
            } else {
                map.put("point", new ArrayList());
            }
        }
        QueryWrapper<BusEvaluate> qw = new QueryWrapper();
        qw.eq("goodsOrderId", goodsOrder.getGoodsOrderId());
        qw.eq("userId", goodsOrder.getUserId());
        BusEvaluate evaluate = busevaluateService.getOne(qw);
        QueryWrapper<BusEvaluate> bus_qw = new QueryWrapper<>();
        bus_qw.eq("forUserId", goodsOrder.getUserId());
        bus_qw.orderByDesc("createTime");
        List<BusEvaluate> busEvaluates = busevaluateService.list(bus_qw);
        if (busEvaluates.size() > 0) {
            map.put("userScore", busEvaluates.get(0).getUserGrade());
        } else {
            map.put("userScore", 5);
        }
        if (ObjectUtils.isNotEmpty(evaluate)) {
            map.put("evaluate", evaluate);
        } else {
            map.put("evaluate", new Object());
        }
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "查看我的订单", notes = "查看我的订单")
    @PostMapping(value = "/order/getorderList")
    public ResultBody getOrderList(PageModel pageModel, String status, String isInvoice) {
        return busGoodsorderService.getOrderList(pageModel, status, isInvoice);
    }
    @ApiOperation(value = "判断是否在高峰期", notes = "判断是否在高峰期")
    @PostMapping(value = "/order/gethight")
    public ResultBody gethight( String dataTime) {
        boolean a=false;
        if (ObjectUtils.isNotEmpty(dataTime)) {
            //判断时间范围是否在高峰期，处在高峰期时候加价配送费
            QueryWrapper<BusSysconfig> qw_con=new QueryWrapper();
            qw_con.in("configType","morningcharge","eveingcharge");
            List<BusSysconfig> busSysconfig=sysconfigService.list(qw_con);
            Long newTime=DateUtils.parseDate(dataTime).getTime();
            if (FlymeUtils.isNotEmpty(busSysconfig)&&busSysconfig.size() > 0) {
                for (BusSysconfig time : busSysconfig) {
                    Long startTime= DateUtils.parseDate(time.getStartHighTime()).getTime();
                    Long endTime=DateUtils.parseDate(time.getEndHighTime()).getTime();
                    if(newTime> startTime&&newTime<endTime){
                        a=true;
                    }
                    if(a){
                      return  ResultBody.ok("您所选时间需要另外加收"+time.getConfigVal()+"元");
                    }
                }
            }
        }else{
            return  ResultBody.failed("送达时间不能为空");
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "取消订单", notes = "取消订单")
    @PostMapping(value = "/order/delOrder")
    public ResultBody delOrder(String goodsOrderId, ResultBody resultBody) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        BusGoodsorder order = busGoodsorderService.getById(goodsOrderId);
        if (FlymeUtils.isEmpty(order)) {
            return ResultBody.failed("订单已不存在");
        }
        if (order.getStatus() == 3) {
            return ResultBody.failed("配送中的单子不能取消");
        }
        if (order.getStatus() == 4||order.getStatus() ==5) {
            return ResultBody.failed("单子已完成不能取消");
        }
        if (order.getStatus() == -1) {
            return ResultBody.failed("单子已取消");
        }

        if (order.getStatus() == 0) {
            //未支付取消订单
            order.setStatus(-1);//单子已失效
            order.setCancelTime(DateUtils.getDateTime());
            order.setCancelType("1");//发单人取消
            boolean b = busGoodsorderService.updateById(order);
            return resultBody.setMsg("取消成功");
        }
        if (FlymeUtils.isNotEmpty(order.getPayType())) {
            if (order.getPayType().equals("aliPay")) {
                if (order.getStatus() == 1 || order.getStatus() == 2) {
                    PayResponse payResponse = payConfigService.getPayResponse(1L, null);
                    RefundOrder refundOrder = new RefundOrder();
                    refundOrder.setOutTradeNo(goodsOrderId);
                    refundOrder.setRefundAmount(order.getRealPaySum());
                    refundOrder.setTotalAmount(order.getRealPaySum());
                    refundOrder.setRefundNo(goodsOrderId);
                    Map<String, Object> resultMap = payResponse.getService().refund(refundOrder);
                    System.out.print("========================================支付宝退款调用======================================");
                    System.out.print(resultMap);
                    //支付宝退款
                    EntityMap map = JsonUtils.jsonToEntityMap(resultMap.get("alipay_trade_refund_response").toString());
                    if (map.get("code").equals("10000")) {
                        //退款成功
                        //抢单完成被客户取消的单子推送给骑手
                        if (order.getStatus() == 2) {
                            BusMsgreceive msgreceive = new BusMsgreceive();
                            msgreceive.setContent("您抢单成功订单号:" + goodsOrderId + "已被用户取消！");
                            msgreceive.setMsgId(goodsOrderId);
                            msgreceive.setMsgType(1);
                            msgreceive.setReceiveUserId(order.getSendUserInfoId());
                            myPushFactory.createBasePush("name2").sendByDeviceToken(String.valueOf(order.getSendUserInfoId()), "订单消息", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！");
                        }
                        order.setStatus(-1);//取消订单
                        order.setCancelTime(DateUtils.getDateTime());
                        order.setCancelType("1");//发单人取消
                        boolean a = busGoodsorderService.updateById(order);
                    }
                    resultBody.setMsg("取消成功");
                }
            }
            if (order.getPayType().equals("wxPay")) {
                System.out.print("========================================微信退款调用入口开始======================================");
                if (order.getStatus() == 1 || order.getStatus() == 2) {
                    RefundOrder refundOrder = new RefundOrder();
                    refundOrder.setOutTradeNo(goodsOrderId);
                    refundOrder.setRefundAmount(order.getRealPaySum());
                    refundOrder.setTotalAmount(order.getRealPaySum());
                    refundOrder.setRefundNo(goodsOrderId);
                    boolean a = weixinRrefund(refundOrder, 3L);
                    System.out.print("========================================微信退款调用======================================");
                    //支付宝退款a
                    if (a) {

                        //抢单完成被客户取消的单子推送给骑手
                        if (order.getStatus() == 2) {
                            BusMsgreceive msgreceive = new BusMsgreceive();
                            msgreceive.setContent("您抢单成功订单号:" + goodsOrderId + "已被用户取消！");
                            msgreceive.setMsgId(goodsOrderId);
                            msgreceive.setMsgType(1);
                            msgreceive.setReceiveUserId(order.getSendUserInfoId());
                            myPushFactory.createBasePush("name2").sendByDeviceToken(String.valueOf(order.getSendUserInfoId()), "订单消息", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！");
                        }
                        //退款成功
                        order.setStatus(-1);//取消订单
                        order.setCancelTime(DateUtils.getDateTime());
                        order.setCancelType("1");//发单人取消
                        boolean b = busGoodsorderService.updateById(order);
                    }
                    resultBody.setMsg("取消成功");
                }
            }
            if (order.getPayType().equals("balance")) {
                if (order.getStatus() == 1 || order.getStatus() == 2) {
                    EntityMap map = new EntityMap();
                    map.put("userId", OpenHelper.getUserId());
                    //余额退款
                    EntityMap use_map = busTradeMapper.findblance(map);
                    BusTrade trade = new BusTrade();
                    if (ObjectUtils.isNotEmpty(use_map)) {
                        BigDecimal balance = use_map.getBigDecimal("balance");
                        trade.setBalance(balance.add(order.getRealPaySum()));
                    }
                    trade.setBusinessId(order.getGoodsOrderId().toString());
                    trade.setTradeExplain("订单退款");
                    trade.setTradeSum(order.getRealPaySum());
                    trade.setTradeType(1);
                    trade.setType(1);
                    trade.setUserId(OpenHelper.getUserId());
                    trade.setStatus(1);
                    boolean a = bustradeService.save(trade);
                    if (a) {
                        //抢单完成被客户取消的单子推送给骑手
                        if (order.getStatus()==2) {
                            BusMsgreceive msgreceive = new BusMsgreceive();
                            msgreceive.setContent("您抢单成功订单号:" + goodsOrderId + "已被用户取消！");
                            msgreceive.setMsgId(goodsOrderId);
                            msgreceive.setMsgType(1);
                            msgreceive.setReceiveUserId(order.getSendUserInfoId());
                            myPushFactory.createBasePush("name2").sendByDeviceToken(String.valueOf(order.getSendUserInfoId()), "订单消息", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！", "您抢单成功订单号为:" + goodsOrderId + "已被用户取消！");

                        }
                        order.setStatus(-1);//取消订单
                        order.setCancelTime(DateUtils.getDateTime());
                        order.setCancelType("1");//发单人取消
                        boolean b = busGoodsorderService.updateById(order);
                    }
                    resultBody.setMsg("取消成功");
                }
            }
        }
        return resultBody;
    }

    /****微信退款***/
    private boolean weixinRrefund(RefundOrder refundOrder, Long payId) {
        try {
            PayResponse payResponse = payConfigService.getPayResponse(3L, "");
            PayConfig payConfig = payResponse.getPayConfig();
            WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
            wxPayConfigStorage.setMchId(payConfig.getPartner());
            wxPayConfigStorage.setAppid(payConfig.getAppId());
            wxPayConfigStorage.setKeyPublic(payConfig.getPublicKey());
            wxPayConfigStorage.setSecretKey(payConfig.getPrivateKey());
            wxPayConfigStorage.setSignType(payConfig.getSignType());
            wxPayConfigStorage.setPayType(payConfig.getPayType().name());
            wxPayConfigStorage.setMsgType(payConfig.getMsgType());
            wxPayConfigStorage.setInputCharset(payConfig.getInputCharset());
            HttpConfigStorage configStorage = new HttpConfigStorage();
            //apiclient_cert.p12证书存放路径，填写绝对路径
            configStorage.setKeystore(payConfig.getKeystorePath());
            configStorage.setStorePassword(payConfig.getPartner());
            configStorage.setMaxTotal(20);
            configStorage.setDefaultMaxPerRoute(10);
            //支付服务
            PayService service = new WxPayService(wxPayConfigStorage, configStorage);
            Map<String, Object> map = service.refund(refundOrder);
            System.out.print("微信退款返回信息" + JsonUtils.beanToJson(map));
            if (map != null && map.get("result_code") != null && "SUCCESS".equals(map.get("result_code").toString())) {
                return true;
            }
        } catch (Exception e) {
            System.out.print("微信退款异常" + e);
        }
        return false;
    }

    @ApiOperation(value = "骑手取消订单", notes = "骑手取消订单")
    @PostMapping(value = "/order/cancelOrderbyrider")
    public ResultBody cancelOrderbyrider(String goodsOrderId, ResultBody resultBody) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            resultBody.setMsg("订单id不能为空");
            return resultBody;
        }
        BusGoodsorder order = busGoodsorderService.getById(goodsOrderId);
        if (FlymeUtils.isEmpty(order)) {
            resultBody.setMsg("订单已不存在");
            return resultBody;
        }
        if (order.getStatus() == 3) {
            resultBody.setMsg("配送中的单子不能取消");
            return resultBody;
        }
        if (order.getStatus() == -1) {
            resultBody.setMsg("单子已取消");
            return resultBody;
        }
        order.setStatus(1);//取消订单
        order.setCancelTime(DateUtils.getDateTime());
        order.setCancelType("2");//骑手取消
        boolean a = busGoodsorderService.updateById(order);
        if (a) {
            resultBody.setMsg("取消成功");
        }
        return resultBody;
    }


    @ApiOperation(value = "支付宝支付订单", notes = "支付宝支付订单")
    @PostMapping(value = "/order/alipayOrder")
    public ResultBody alipayOrder(String goodsOrderId, String payType, ResultBody resultBody) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            resultBody.setMsg("订单id不能为空");
            return resultBody;
        }
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        return ResultBody.ok(busGoodsorderService.AliWEI(payType, busGoodsorder));
    }

    @ApiOperation(value = "余额支付", notes = "余额支付")
    @PostMapping(value = "/order/balancePayOrder")
    public ResultBody balancePayOrder(String goodsOrderId, ResultBody resultBody) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        if (busGoodsorder.getRealPaySum().doubleValue() == 0) {
            busGoodsorder.setStatus(1);
        } else {
            Map userMap = new HashMap();
            userMap.put("userId", OpenHelper.getUserId());
            EntityMap use_map = tradeMapper.findblance(userMap);
            Double sum = busGoodsorder.getRealPaySum().doubleValue();
            if (FlymeUtils.isEmpty(use_map) || use_map.getBigDecimal("balance").doubleValue() == 0 || use_map.getBigDecimal("balance").doubleValue() < sum) {
                return ResultBody.failed("账户余额不足");
            }
            BigDecimal balance = use_map.getBigDecimal("balance");
            BigDecimal newbalance = BigDecimal.valueOf(balance.doubleValue() - sum);
            BusTrade trade = new BusTrade();
            trade.setBalance(newbalance);
            trade.setBusinessId(goodsOrderId);
            trade.setTradeExplain("订单支付");
            trade.setTradeId(Long.parseLong(goodsOrderId));
            trade.setTradeSum(busGoodsorder.getRealPaySum());
            trade.setTradeType(1);
            trade.setType(0);
            trade.setUserId(OpenHelper.getUserId());
            trade.setStatus(1);
            boolean a = bustradeService.save(trade);
            if (a) {
                busGoodsorder.setStatus(1);
                busGoodsorder.setPayTime(DateUtils.getDateTime());
                busGoodsorder.setPayType("balance");//余额支付
                busGoodsorderService.saveOrUpdate(busGoodsorder);
                resultBody.setMsg("支付成功");
            }
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "抢单", notes = "抢单")
    @PostMapping(value = "/order/grab")
    public ResultBody grab(String goodsOrderId) {
        EntityMap map = new EntityMap();
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        map.put("goodsOrderId", goodsOrderId);
        ResultBody body = busGoodsorderService.grob(map);
        return body;
    }

    @ApiOperation(value = "取件", notes = "取件")
    @PostMapping(value = "/order/pickGoods")
    public ResultBody pickGoods(String goodsOrderId, ResultBody resultBody) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        //检验单子状态
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        if (busGoodsorder.getStatus() != 2) {
            return ResultBody.failed("订单状态不正确");
        }
        if (busGoodsorder.getStatus() == -1) {
            return ResultBody.failed("订单已取消");
        }

        return ResultBody.ok();
    }

    @ApiOperation(value = "确认取件", notes = "确认取件")
    @PostMapping(value = "/order/pickupGoods")
    public ResultBody pickupGoods(String goodsOrderId, String code, String goodImage, ResultBody resultBody) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        //检验单子状态
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        QueryWrapper<BusRider> qw = new QueryWrapper();
        qw.eq("userId", busGoodsorder.getSendUserInfoId());
        BusRider rider = busRiderService.getOne(qw);
        if (FlymeUtils.isNotEmpty(rider)) {
            rider.setStatus(2);//骑手状态配送中
            busRiderService.saveOrUpdate(rider);//更新状态
        }
        QueryWrapper<BusIdentity> qw_2 = new QueryWrapper();
        qw_2.eq("userId", busGoodsorder.getUserId());
        BusIdentity busIdentity = identityService.getOne(qw_2);
        //商家发单且设置不发验证码
        Integer affirmcode = RandomUtil.randomInt(100000, 999999);
        if (FlymeUtils.isNotEmpty(busIdentity)&&busIdentity.getUserType().equals("2")) {
            //判断是否未商家用户的单子且开关为关闭
            if (busIdentity.getCodeStatus().equals("0")) {
                affirmcode = 111111;
            } else {
                String handlerName = map.get(SettingConstant.SMSCODE_HANDLER, "");
                //给发件人发送短信
                SmsSendHandler smsSendHandler = SpringContextHolder.getHandler(handlerName, SmsSendHandler.class);
                Map<String, Object> params = new HashedMap();
                params.put("code", affirmcode);
                smsSendHandler.sendSms(busGoodsorder.getReceiptMobile(), "SMS_181202285", params);
            }
        }else{
                String handlerName = map.get(SettingConstant.SMSCODE_HANDLER, "");
                //给发件人发送短信
                SmsSendHandler smsSendHandler = SpringContextHolder.getHandler(handlerName, SmsSendHandler.class);
                Map<String, Object> params = new HashedMap();
                params.put("code", affirmcode);
                smsSendHandler.sendSms(busGoodsorder.getReceiptMobile(), "SMS_181202285", params);
         }
        busGoodsorder.setStatus(3);//配送中
        busGoodsorder.setPickupTime(DateUtils.getDateTime());
        busGoodsorder.setAffirmCode(String.valueOf(affirmcode));
        busGoodsorder.setGoodImage(goodImage);
        BusMsgreceive msgreceive = new BusMsgreceive();
        msgreceive.setContent("您订单号为:" + goodsOrderId + "已取件完成！");
        msgreceive.setMsgId(goodsOrderId);
        msgreceive.setMsgType(1);
        msgreceive.setReceiveUserId(busGoodsorder.getUserId());
        myPushFactory.createBasePush("name1").sendByDeviceToken(String.valueOf(busGoodsorder.getUserId()), "您订单号为:" + goodsOrderId +"已取件成功！", "订单消息", "您订单号为:" + goodsOrderId + "已取件成功！", "您订单号为:" + goodsOrderId + "已取件成功！");
        //保存发送消息记录
        busmsgreceiveService.save(msgreceive);
        busGoodsorderService.saveOrUpdate(busGoodsorder);
        return ResultBody.ok();
    }

    @ApiOperation(value = "完成取件", notes = "完成取件")
    @PostMapping(value = "/order/completeOrder")
    public ResultBody completeOrder(String goodsOrderId, ResultBody resultBody) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        //检验单子状态
        String show = "";
        //检验单子状态
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        if (busGoodsorder.getStatus() != 3) {
            return ResultBody.failed("订单状态不正确");
        }
        if (busGoodsorder.getAffirmCode().equals("111111")) {
            show = "1";
        } else {
            show = "0";
        }
        return ResultBody.ok(show);
    }

    @ApiOperation(value = "确认完成", notes = "确认完成")
    @PostMapping(value = "/order/affirmOrder")
    public ResultBody affirmOrder(String goodsOrderId, String affirmcode) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            return ResultBody.failed("订单id不能为空");
        }
        //检验单子状态
        BusGoodsorder busGoodsorder = busGoodsorderService.getById(goodsOrderId);
        if (FlymeUtils.isNotEmpty(busGoodsorder.getAffirmCode())) {
            if (!busGoodsorder.getAffirmCode().equals("111111")) {
                    if (FlymeUtils.isEmpty(affirmcode)) {
                        return ResultBody.failed("收件码不能为空");
                    }
                    if (!busGoodsorder.getAffirmCode().equals(affirmcode)) {
                        return ResultBody.failed("收件码不正确");
                    }
                }

                    busGoodsorder.setStatus(4);//订单完成
                    busGoodsorder.setDeliveryTime(DateUtils.getDateTime());
                    busGoodsorder.setSendlastTime(DateUtils.getDateTime());
                    busGoodsorder.setIsInvoice(0);
                    EntityMap map = new EntityMap();
                    map.put("userInfoId", OpenHelper.getUserId());
                    Double a = 0.00;
                    QueryWrapper<BusProfit> ft = new QueryWrapper();
                    ft.eq("userInfoId", OpenHelper.getUserId());
                    List<BusProfit> list_q = busProfitService.list(ft);
                    BusProfit busProfit = new BusProfit();
                    EntityMap map1 = busprofitmapper.findblance(map);
                    if (FlymeUtils.isNotEmpty(map1)) {
                        BigDecimal balance = map1.get("balance");
                        a = balance.doubleValue() + busGoodsorder.getRiderCommission().doubleValue();
                        busProfit.setBalance(BigDecimal.valueOf(a));
                    } else {
                        busProfit.setBalance(busGoodsorder.getRiderCommission());
                    }
                    myPushFactory.createBasePush("name1").sendByDeviceToken(String.valueOf(busGoodsorder.getUserId()), "您订单号为:" + goodsOrderId + "已确认完成！", "订单消息", "您订单号为:" + goodsOrderId + "已确认完成！", "您订单号为:" + goodsOrderId + "已确认完成！");
                    busProfit.setBusinessId(busGoodsorder.getGoodsOrderId());
                    busProfit.setUserInfoId(busGoodsorder.getSendUserInfoId());
                    busProfit.setFromUserInfoId(busGoodsorder.getUserId());
                    busProfit.setProfitExplain("配送服务费收入");
                    busProfit.setProfitSum(busGoodsorder.getRiderCommission());
                    busProfit.setProfitType(1);
                    busProfit.setType("1");
                    busProfit.setStatus(1);
                    busProfit.setProfitWay("配送服务费收入");
                    busProfitService.saveOrUpdate(busProfit);
                    busGoodsorderService.saveOrUpdate(busGoodsorder);


        }
           return ResultBody.ok();
    }
    @ApiOperation(value = "查看我配送的订单", notes = "查看我配送的订单")
    @PostMapping(value = "/order/riderList")
    public ResultBody riderList(PageModel pageModel) {
        return busGoodsorderService.sendUserList(pageModel,null,null);

    }

    @ApiOperation(value = "订单评价", notes = "订单评价")
    @PostMapping(value = "/order/comment")
    public ResultBody comment(String goodsOrderId, int serveGrade, int speedGrade, String evaluateContent) {
        if (FlymeUtils.isEmpty(goodsOrderId)) {
            ResultBody.failed("订单id不能为空");
        }
        BusGoodsorder order = busGoodsorderService.getById(goodsOrderId);
        if (FlymeUtils.isEmpty(order)) {
            ResultBody.failed("订单id不正确");
        }
        if (order.getStatus() != 4) {
            ResultBody.failed("订单状态不正确");
        }
        BusEvaluate busEvaluate = new BusEvaluate();
        busEvaluate.setUserId(order.getUserId());
        busEvaluate.setForUserId(order.getSendUserInfoId());
        busEvaluate.setGoodsOrderId(Long.parseLong(goodsOrderId));
        busEvaluate.setServeGrade(BigDecimal.valueOf(serveGrade));
        busEvaluate.setSpeedGrade(BigDecimal.valueOf(speedGrade));
        busEvaluate.setEvaluateContent(evaluateContent);
        boolean a = busevaluateService.save(busEvaluate);
        if (a) {
            ResultBody.msg("评价成功");
            order.setStatus(5);
            busGoodsorderService.saveOrUpdate(order);
        }
        return ResultBody.ok();

    }

    @ApiOperation(value = "抢单列表", notes = "抢单列表")
    @PostMapping(value = "/order/orderList")

    public ResultBody grabList_1(double lng, double lat, double distance, String deliveryTime, String commission,String city,String district ,PageModel pageModel) {
        EntityMap map = new EntityMap();
        if(FlymeUtils.isNotEmpty(lng)&&FlymeUtils.isNotEmpty(lat)) {
            List<EntityMap> orderList = busGoodsorderService.findListDataByDistance(lng, lat, city, district, distance, deliveryTime, commission, pageModel);
            map.put("orderList", orderList);
        }else{
           return  ResultBody.failed("获取不到经纬度");
        }
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "首页抢单", notes = "首页抢单")
    @PostMapping(value = "/order/grabList")
    public ResultBody grabList(double lng, double lat, String distance, String deliveryTime, String commission) {
        EntityMap map = new EntityMap();
        if(FlymeUtils.isNotEmpty(lng)&&FlymeUtils.isNotEmpty(lat)) {
            int count = busGoodsorderService.findCtnDataByDistance(lng, lat, distance, deliveryTime, commission);
            map.put("orderCount", count);
        }else{
            return  ResultBody.failed("获取不到经纬度");
        }
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "订单统计日账单", notes = "订单统计")
    @PostMapping(value = "/order/daybils")
    public ResultBody daybils(PageModel pageModel) {
        Long userId = OpenHelper.getUserId();
        String startDate = DateUtils.getLastDay(new Date(), "yyyy-MM-dd");
        String endDate = DateUtils.formatDate();
        EntityMap map = new EntityMap();
        EntityMap completeOrder = busGoodsorderService.findGoodsOrderCount(userId, startDate, endDate);
        EntityMap cancelOrder = busGoodsorderService.findCancelOrderCount(userId, startDate, endDate);
        ResultBody orderDetail = busGoodsorderService.sendUserList(pageModel,startDate,endDate);
        if (FlymeUtils.isEmpty(completeOrder)) {
            map.put("completeOrder", new Object());
        } else {
            map.put("completeOrder", completeOrder);
        }
        if (FlymeUtils.isEmpty(cancelOrder)) {
            map.put("cancelOrder", new Object());
        } else {
            map.put("cancelOrder", cancelOrder);
        }
        map.put("orderDetail", orderDetail);
        return ResultBody.ok(map);

    }

    @ApiOperation(value = "订单统计月账单", notes = "订单统计月账单")
    @PostMapping(value = "/order/monthbils")
    public ResultBody monthbils() {
        Long userId = OpenHelper.getUserId();
        List<EntityMap> monthbills = busGoodsorderService.findmothbils(userId);
        return ResultBody.ok(monthbills);
    }
    /**
     * 小程序支付（充值支付）
     *
     *
     */
    @RequestMapping(value = "/order/pay")
    @LoginRequired
    public ResultBody pay( HttpServletRequest request, HttpServletResponse response,
                    String orderId, BigDecimal money) {
        ResultBody body=new ResultBody();
        Long userId = OpenHelper.getUserId();
        AppAccount account = accountService.getAccount(userId, "WEIXIN");
        BusGoodsorder shoporder = busGoodsorderService.getById(orderId);
        if (ObjectUtils.isEmpty(shoporder)) {
            return ResultBody.failed("订单不存在");
        }
        if (ObjectUtils.isNotEmpty(shoporder) && shoporder.getStatus() != 0) {
            return ResultBody.failed("订单状态不正确");
        }
        if (money.compareTo(shoporder.getRealPaySum()) == 0) {

            Integer money2 = shoporder.getRealPaySum().multiply(new BigDecimal("100")).intValue();
             body=cx_recharge(request, response, orderId, "微信支付", money2,
                "https://esong/app/api/order/pay_back", "1", account.getAccount());
        }
     return body;
    }
    /**
     * 小程序支付回调
     *
     * @throws Exception
     */
    @RequestMapping(value = "/order/pay_back")
    @LoginRequired
    public ResultBody pay_back( HttpServletRequest request, HttpServletResponse response,
                           String orderId, BigDecimal money) throws Exception {
        ResultBody body=new ResultBody();
        //查询订单并修改订单状态
        BusGoodsorder shoporder = busGoodsorderService.getById(orderId);
        shoporder.setStatus(1);
        shoporder.setPayType("WEIXIN");
        shoporder.setPayTime(DateUtils.getDateTime());
        busGoodsorderService.saveOrUpdate(shoporder);
        return body;
    }


    /**
     * 小程序端支付
     * @param request
     * @param response
     * @param out_trade_no
     * @param body
     * @param total_fee
     * @param notify_url
     * @param attach
     * @return
     */
    public ResultBody  cx_recharge(HttpServletRequest request, HttpServletResponse response,String out_trade_no, String body, Integer total_fee, String notify_url, String attach, String openid) {
        PayParam pi = new PayParam();
        String nonce_str = TenpayUtil.getNonceStr();
        String spbill_create_ip = PcUtils.getIpAddr();
        String trade_type = "JSAPI";
        // 对以下字段进行签名
        SortedMap<String, Object> packageParams = new TreeMap<String, Object>();
        packageParams.put("appid", appid);
        packageParams.put("attach", attach);
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("notify_url", notify_url);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("total_fee", total_fee);
        packageParams.put("trade_type", trade_type);
        packageParams.put("openid", openid);
        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(appid, appsecret, mch_key);
        String sign = reqHandler.createSign(packageParams);// 获取签名
        String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<attach>" + attach + "</attach>" + "<body><![CDATA[" + body + "]]></body>" + "<mch_id>" + mch_id + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<notify_url>" + notify_url + "</notify_url>" + "<openid>" + openid + "</openid>" + "<out_trade_no>" + out_trade_no + "</out_trade_no>" + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" + "<total_fee>" + total_fee + "</total_fee>" + "<trade_type>" + trade_type + "</trade_type>" + "<sign>" + sign + "</sign>" +"</xml>";
        Boolean tag = GetWxOrderno.getPayNo(pi, PAY_UNIFIEDORDER, xml);
        if (tag) {
            // 获取到prepayid后对以下字段进行签名最终发送给app
            SortedMap<String, Object> finalpackage = new TreeMap<String, Object>();
            String timestamp = DateUtils.getTimestampStr();
            finalpackage.put("appId", appid);
            finalpackage.put("timeStamp", timestamp);
            finalpackage.put("nonceStr", nonce_str);
            finalpackage.put("package", "prepay_id="+pi.getPrepayId());
            finalpackage.put("signType", "MD5");
            String finalsign = reqHandler.createSign(finalpackage);
            pi.setTimeStamp(timestamp);
            pi.setSign(finalsign);
            pi.setNonceStr(nonce_str);
            pi.setAppId(appid);
            return  ResultBody.ok(pi);
        } else {
            return   ResultBody.failed(pi.getMsg());
        }

    }
    public static void main(String[] args) {
        AliyunSmsSenderImpl aliyunSmsSender = new AliyunSmsSenderImpl();
        SmsMessage smsNotify = new SmsMessage();
        smsNotify.setPhoneNum("18739941307");
        smsNotify.setSignName("玩了么商城");
        smsNotify.setTplCode("SMS_174814144");
        smsNotify.add("code", "1254587");
        aliyunSmsSender.send(smsNotify);    }




}
